package com.qixiang.usercenter.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qixiang.usercenter.exception.BusinessException;
import com.qixiang.usercenter.exception.ThrowUtils;
import com.qixiang.usercenter.model.entity.SysUser;
import com.qixiang.usercenter.service.SysUserService;
import com.qixiang.usercenter.mapper.SysUserMapper;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static com.qixiang.usercenter.exception.ErrorCode.PARAMS_ERROR;

/**
 * @author 14326
 * @description 针对表【sys_user(系统用户表)】的数据库操作Service实现
 * @createDate 2025-03-31 18:24:29
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Resource
    SysUserMapper sysUserMapper;

    @Override
    public long userRegister(String username, String accountant, String password, String confirmPassword) throws BusinessException {
        //判空
        ThrowUtils.throwIf(StrUtil.hasBlank(username, accountant, password, confirmPassword),PARAMS_ERROR);

        //长度限制
        if (password.length() < 6 || accountant.length() < 2 || confirmPassword.length() < 6) {
            return -1;
        }
        //二次密码确认
        if (!password.equals(confirmPassword)) {
            return -1;
        }
        //账户只能有字母、数字、下划线
        if (accountant.matches(".*[\\W_]+.*")) {
            return -1;
        }
        //账户唯一性
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getLoginAccount, accountant);

        if (sysUserMapper.exists(lambdaQueryWrapper)) {
            return -1;
        }
        //持久化
        SysUser user = new SysUser();
        user.setUsername(username);
        user.setLoginAccount(accountant);
        //对密码进行加密BCrypt
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        // 哈希密码（自动加盐）
        String hashedPassword = encoder.encode(password);
        user.setPassword(hashedPassword);

        try {
             sysUserMapper.insert(user);
             return user.getId();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}




